package com.onix.scalecamerapreview.translate.msOcr;


import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;


import com.onix.scalecamerapreview.MyApplication;

import java.io.IOException;
import java.io.InputStream;


import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class RxImageUtils {

    public static Observable<Bitmap> getBitmap(final Uri uri, final int defaultWidth, final int defaultHeight){
        Observable<Bitmap> bitmapObservable = Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(ObservableEmitter<Bitmap> e) throws Exception {
                BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
                onlyBoundsOptions.inJustDecodeBounds = true;
                onlyBoundsOptions.inDither = true;//optional
                InputStream input = MyApplication.getInstance().getContentResolver().openInputStream(uri);
                BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
                int bitmapDegree = getBitmapDegree(uri);

                Log.d("AAA","旋转角度 "+bitmapDegree);
                input.close();
                int originalWidth = onlyBoundsOptions.outWidth;
                int originalHeight = onlyBoundsOptions.outHeight;
                Log.d("AAA"," originalWidth "+originalWidth+" originalHeight "+originalHeight );
                if (originalWidth == -1) {
                    originalWidth = defaultWidth;
                }
                if (originalHeight == -1) {
                    originalHeight = defaultHeight;
                }
                int inSampleSize = 1; // 1是不缩放
                // 计算宽高缩放比例
                int inSampleSizeW = originalWidth/defaultWidth;
                int inSampleSizeH =originalHeight/defaultHeight;
                // 最终取大的那个为缩放比例，这样才能适配，例如宽缩放3倍才能适配屏幕，而
                // 高不缩放就可以，那样的话如果按高缩放，宽在屏幕内就显示不下了
                if (inSampleSizeW > inSampleSizeH) {
                    inSampleSize = inSampleSizeW;
                }else {
                    inSampleSize = inSampleSizeH;
                }
                Log.d("AAA","inSampleSize "+inSampleSize);
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                bitmapOptions.inDither = true;//optional
                bitmapOptions.inSampleSize = inSampleSize;
                bitmapOptions.inJustDecodeBounds = false;
                bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;//optional
                input = MyApplication.getInstance().getContentResolver().openInputStream(uri);
                Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
                input.close();
                originalHeight = bitmap.getHeight();
                originalWidth = bitmap.getWidth();
                Log.d("AAA"," originalWidth1 "+originalWidth+" originalHeight1 "+originalHeight );
                Log.d("AAA","defaultWidth "+defaultWidth + " defaultHeight "+defaultHeight);
                float scale = 1.0f;
                if(originalHeight>=originalWidth){
                    //缩放
                    scale =  defaultHeight * 1.0f/originalHeight * 1.0f ;
                }else {
                    scale = defaultWidth * 1.0f /originalWidth * 1.0f;
                }
                if(scale>1.0f){
                    scale = 1.0f;
                }
                Matrix matrix = new Matrix();
                Log.d("AAA","scale "+scale);
                matrix.postScale(scale, scale);
                if(bitmapDegree == 270){
                    matrix.setRotate(-90);
                }else if(bitmapDegree == 90){
                    matrix.setRotate(90);
                }else if(bitmapDegree == 180){
                    matrix.setRotate(180);
                }
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

                e.onNext(bitmap);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        return bitmapObservable;
    }



    /**
     * 获取图片的旋转角度
     *
     * @param uri 图片的输入流
     * @return 图片的旋转角度
     */
    public static int getBitmapDegree(Uri uri) {
        int degree = 0;
        try {
            String realPathFromURI = getRealPathFromURI(uri);
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(realPathFromURI);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public  static String getRealPathFromURI( Uri contentURI) {
        String result;
        Cursor cursor = MyApplication.getInstance().getContentResolver().query(contentURI,
                new String[]{MediaStore.Images.ImageColumns.DATA},//
                null, null, null);
        if (cursor == null) {
            result = contentURI.getPath();
        }else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(index);
            cursor.close();
        }
        return result;
    }
}
